package com.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.UUID;

@Controller
public class FileController {
    @Value( "${uploadFilePath}" )
    private  String uploadFilePah ;

    //单个文件下载
    @RequestMapping("/downFile")
    public void  downFile(String fileName, HttpServletRequest request, HttpServletResponse response ){
        try {
            //文件编码问题处理
            fileName = URLDecoder.decode( fileName,"utf-8" );
            response.setContentType( request.getServletContext().getMimeType( fileName ) );
//            response.setContentType( "image/jpeg" );
            //设置header信息
            response.setHeader( "Content-Disposition","attachment;filename="+fileName );
            //获取准备下载的文件
            String fileDir = request.getServletContext().getRealPath( "/WEB-INF/assets/file" );
            File file = new File( fileDir,fileName );
            //获取文件的长度
            //设置输出长度
            response.setHeader("Content-Length", String.valueOf(file.length()));
            //读取文件
            //输出文件
            BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) );
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream( outputStream );
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read( buff, 0, buff.length ))) {
                bos.write( buff, 0, bytesRead );
            }
            bis.close();
            bos.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @RequestMapping(value="/fileUpLoad")
    @ResponseBody
    public String testUpload(HttpServletRequest request,@RequestParam("file") CommonsMultipartFile file) throws Exception{
        ServletContext servletContext = request.getServletContext();//获取ServletContext的对象 代表当前WEB应用
        String realPath = servletContext.getRealPath("/WEB-INF/file/upload");//得到文件上传目的位置的真实路径
        File file1 = new File(realPath);
        if(!file1.exists()){
            file1.mkdirs();   //如果该目录不存在，就创建此抽象路径名指定的目录。
        }
        String prefix = UUID.randomUUID().toString();
        prefix = prefix.replace("-","");
        String fileName = prefix+"_"+file.getOriginalFilename();//使用UUID加前缀命名文件，防止名字重复被覆盖
        File uploadFile = new File( realPath, fileName );
        file.transferTo( uploadFile );
        return "upload file success";
    }

    @RequestMapping(value="/mulitfileUpLoad")
    @ResponseBody
    public String mulitfileUpLoad(HttpServletRequest request, @RequestParam(value="desc",required=false) String desc, @RequestParam("file") CommonsMultipartFile[] files) throws Exception{
        for (CommonsMultipartFile file : files){
            ServletContext servletContext = request.getServletContext();//获取ServletContext的对象 代表当前WEB应用
            String realPath = servletContext.getRealPath("/WEB-INF/file/upload");//得到文件上传目的位置的真实路径
            File file1 = new File(realPath);
            if(!file1.exists()){
                file1.mkdirs();   //如果该目录不存在，就创建此抽象路径名指定的目录。
            }
            String prefix = UUID.randomUUID().toString();
            prefix = prefix.replace("-","");
            String fileName = prefix+"_"+file.getOriginalFilename();//使用UUID加前缀命名文件，防止名字重复被覆盖
            File uploadFile = new File( realPath, fileName );
            file.transferTo( uploadFile );
        }
        return "upload file success";
    }
}
